package com.yc.cloud.wps.utils;

import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.pdf.DocSaveOptions;
import com.aspose.pdf.Document;
import com.aspose.pdf.ExcelSaveOptions;
import com.aspose.pdf.PptxSaveOptions;
import com.aspose.slides.PdfOptions;
import com.aspose.slides.Presentation;
import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


public class AsposeUtils {

    private AsposeUtils() {
    }

    private static AsposeUtils ourInstance = new AsposeUtils();

    public static AsposeUtils getInstance() {
        return ourInstance;
    }

    public boolean pdf2word(String pdfPath, String dstPath) {
        Document doc = null;
        try {
            doc = new Document(pdfPath);
          /*  doc.setAbsentFontTryToSubstitute(true);
            doc.set*/
            //   doc.setCenterWindow(true);
            DocSaveOptions saveOptions = new DocSaveOptions();
      /*      System.out.println(JSON.toJSON(saveOptions));
            saveOptions.setAddReturnToLineEnd(true);
            saveOptions.setRecognizeBullets(true);
            saveOptions.setRelativeHorizontalProximity(15);
            saveOptions.setExtractOcrSublayerOnly(true);
            saveOptions.setMaxDistanceBetweenTextLines(5f);*/
            saveOptions.setMode(DocSaveOptions.RecognitionMode.Flow);
            if (dstPath.endsWith(".doc")) {
                saveOptions.setFormat(DocSaveOptions.DocFormat.Doc);
            } else {
                saveOptions.setFormat(DocSaveOptions.DocFormat.DocX);
            }
            // long starTime = System.currentTimeMillis();
            doc.save(dstPath, saveOptions);
            //   System.out.println("pdf2word spend times "+(System.currentTimeMillis()-starTime));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean pdf2xlxs(String path, String dstPath) {
        try {
            // Load PDF document
            Document pdfDocument = new Document(path);
// Initialize ExcelSaveOptions
            ExcelSaveOptions options = new ExcelSaveOptions();
// Set output format
            options.setFormat(ExcelSaveOptions.ExcelFormat.XLSX);

// Save output file
            pdfDocument.save(dstPath, options);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean pdf2pptx(String pdfPath, String pptPath) {
        Document pdfDocument = null;
        try {
            long startTime = System.currentTimeMillis();
            // Load PDF document
            pdfDocument = new Document(pdfPath);
            //  pdfDocument.optimize();
            PptxSaveOptions pptxOptions = new PptxSaveOptions();
            //通過圖片形式輸出
            // pptxOptions.setSlidesAsImages(true);
            //轉換進度
            // pptxOptions.setCustomProgressHandler(new ShowProgressOnConsole());
            pptxOptions.setOptimizeTextBoxes(true);
            //pptxOptions.TryMergeAdjacentSameBackgroundImages = true;
            //  pptxOptions.setImageResolution(400);
            pptxOptions.setSeparateImages(true);
            // Convert PDF to PPTX
            pdfDocument.save(pptPath, pptxOptions);
            System.out.println("pdf2pptx spend times :" + (System.currentTimeMillis() - startTime));
            pdfDocument.close();
        } catch (Exception e) {
            e.printStackTrace();
            if (pdfDocument != null) pdfDocument.close();
            return false;
        }
        return true;
    }

    public boolean word2pdf(String path, String outPath) {
        long startTime = System.currentTimeMillis();
        FileOutputStream os = null;
        try {
            File file = new File(outPath);
            os = new FileOutputStream(file);
            // Address是将要被转化的word文档
            com.aspose.words.Document doc = new com.aspose.words.Document(path);
            com.aspose.words.PdfSaveOptions saveOptions = new com.aspose.words.PdfSaveOptions();
            saveOptions.setEmbedFullFonts(true);
            doc.save(os, com.aspose.words.SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("===> word2pdf  times: " + ((System.currentTimeMillis() - startTime) / 1000) + " 秒");
        return true;
    }


    public boolean excel2pdf(String path, String output) {
        try {
            long old = System.currentTimeMillis();
            // 原始excel路径
            Workbook wb = new Workbook(path);
            com.aspose.cells.PdfSaveOptions saveOptions = new PdfSaveOptions();
            //重点，设置所有列放在一页里，会自动适应宽度
            // saveOptions.setAllColumnsInOnePagePerSheet(true);
//            saveOptions.setCellAutoFit(true);
            saveOptions.setOnePagePerSheet(true);
            // saveOptions.setImageType(ImageFormat.getJpeg());
            FileOutputStream fileOS = new FileOutputStream(new File(output));
            wb.save(fileOS, saveOptions);
            fileOS.close();
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒"); //转化用时
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean ppt2pdf(String path, String output) {
        Presentation ppt = null;
        FileOutputStream fileOS = null;
        try {
            ppt = new Presentation(path);
            fileOS = new FileOutputStream(new File(output));
            PdfOptions options = new PdfOptions();
          /*  options.setBestImagesCompressionRatio(true);
            byte jpdQuality = 70;
            options.setJpegQuality(jpdQuality);*/
            ppt.save(fileOS, com.aspose.slides.SaveFormat.Pdf, options);

            fileOS.close();
            ppt.dispose();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            if (fileOS != null) {
                try {
                    fileOS.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (ppt != null) {
                ppt.dispose();
            }

        }
        return false;
    }

    public boolean pdf2Html(String pdfPath, String output, float scale) {
        StringBuffer buffer = new StringBuffer();
        FileOutputStream fos = null;
        PDDocument document = null;
        File pdfFile;
        int size;
        BufferedImage image;
        buffer.append("<!doctype html>\r\n");
        buffer.append("<head>\r\n");
        buffer.append("<title>文档预览</title>\r\n");
        buffer.append("<meta charset=\"UTF-8\">\r\n");
        buffer.append("</head>\r\n");
        buffer.append("<body style=\"background-color:gray;\">\r\n");
        buffer.append("<style>\r\n");
        buffer.append(".imgdemo{display: table-cell;vertical-align: middle;text-align: center;}\r\n");
        buffer.append("img {background-color:#fff; text-align:center; width:50%; max-width:200%;margin-top:6px;}\r\n");
        buffer.append("</style>\r\n");
        buffer.append("<div class=\"imgdemo\">\r\n");
        document = new PDDocument();
        //pdf附件
        pdfFile = new File(pdfPath);
        try {
            document = PDDocument.load(pdfFile, (String) null);
            size = document.getNumberOfPages();
            Long start = System.currentTimeMillis(), end = null;
            System.out.println("===>pdf : " + pdfFile.getName() + " , size : " + size + " 页");
            PDFRenderer reader = new PDFRenderer(document);
            for (int i = 0; i < size; i++) {
                image = reader.renderImage(i, scale);
                String base64ImageData = encodeToString(image, "jpg");
                String imagePath = "data:image/png;base64," + base64ImageData;
                ;
                buffer.append("<img src=\"" + imagePath + "\"/>\r\n");
            }
            buffer.append("<div/>\r\n");
            buffer.append("</body>\r\n");
            buffer.append("</html>");
            end = System.currentTimeMillis() - start;
            System.out.println("===> Reading pdf times: " + (end / 1000) + " 秒");
            //生成网页文件
            fos = new FileOutputStream(output);
            fos.write(buffer.toString().getBytes());
            fos.flush();
            buffer.setLength(0);
        } catch (Exception e) {
            System.out.println("===>Reader parse pdf to jpg error : " + e.getMessage());
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (document != null) {
                    document.close();
                    document = null;
                }
            } catch (IOException io) {
                io.printStackTrace();
            }
        }
        return true;
    }


    public boolean word2html(String path, String outPath) {
        // Load the document from disk.
        com.aspose.words.Document doc = null;
        try {
            doc = new com.aspose.words.Document(path);
            // Save the document into HTML.
            doc.save(outPath, com.aspose.words.SaveFormat.HTML);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();
            imageString = Base64.encodeBase64String(imageBytes);
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

    public static void main(String[] args) {
        AsposeUtils.getInstance().word2pdf("/Users/jackgu/Downloads/test.docx", "/Users/jackgu/Downloads/test2.pdf");
    }
}
